<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 01:21:39
 * @LastEditTime: 2023-10-31 15:47:06
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Traits;

use App\Models\ComprehensiveCarry;
use App\Models\ComprehensiveCarryCarDetail;
use App\Models\ComprehensiveCarryDetails;
use App\Repositories\ComprehensiveCarryRepository;
use Illuminate\Support\Facades\App;

trait CarryCarDetailTrait
    {
    //编号所放路径  ['indent'=>['main'=>'code'=>'']]
    private $_source_code_field = ["code" => ""];
    public function getSourceCodeField()
        {
        $key = $this->_source_code_field;
        if (property_exists(__CLASS__, "sourceCodeField"))
            $key = $this->sourceCodeField;
        return $key;
        }
    public function getSourceCode()
        {
        $model        = $this;
        $source_route = $this->getSourceCodeField();
        if (is_string($source_route)) {
            return $source_route;
            }
        foreach ($source_route as $key => $value) {
            return $this->diGuiGetCode($key, $value, $model);
            }
        }
    public function diGuiGetCode($key, $value, $model)
        {
        if (is_array($value)) {
            foreach ($value as $k => $v)
                return $this->diGuiGetCode($k, $v, $model->{$key});
            }
        return $model->{$key};
        }
    public function createCarCarryDetail(
        $material_id,
        $dyelot,
        $type_id,
        $batchno,
        $color_name,
        $auxiliary_quantity,
        $quantity,
        $source_model,
        $source_key,
        $source_value
    ) {
        return ComprehensiveCarryCarDetail::updateOrCreate([
            'source_model' => $source_model,
            'source_key'   => $source_key,
            'source_value' => $source_value,
        ], [
            'material_id'        => $material_id,
            'dyelot'             => $dyelot,
            'type_id'            => $type_id,
            'batchno'            => $batchno,
            'color_name'         => $color_name,
            'auxiliary_quantity' => $auxiliary_quantity ?? 0,
            'quantity'           => $quantity ?? 0,
            'carry_count'        => 1,
            'car_count'          => 1,
            'code'               => $this->getSourceCode()
        ]);
        }
    public function removeCarCarryDetail($source_model = null, $source_key = null, $source_value = null)
        {
        $this->getCar_carry_detailAttribute($source_model, $source_key, $source_value)?->delete();
        }
    public function getCar_carry_detailAttribute($source_model = null, $source_key = null, $source_value = null)
        {
        return ComprehensiveCarryCarDetail::whereSource_model($source_model ?? $this::class)->whereSource_key($source_key ?? "id")->whereSource_value($source_value ?? $this->id)->first();
        }

    }